package xin.i18n.interceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;
import xin.i18n.starter.I18nProperties;
import xin.i18n.util.LocaleType;
import xin.i18n.util.ResolverType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * <pre>
 * 本地化信息拦截器，用于加载本地化信息
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2019/11/26
 */
public class LocaleChangeInterceptor extends HandlerInterceptorAdapter {
	protected final Log logger = LogFactory.getLog(this.getClass());
	private I18nProperties.Interceptor proper;
	
	public LocaleChangeInterceptor() {
	
	}
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
		String newLocale = resolveLocal(request);
		if (newLocale != null) {
			LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
			if (localeResolver == null) {
				throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
			}
			
			try {
				localeResolver.setLocale(request, response, this.parseLocaleValue(newLocale));
			} catch (IllegalArgumentException var7) {
				this.logger.debug("Ignoring invalid locale value [" + newLocale + "]: " + var7.getMessage());
			}
		}
		
		return true;
	}
	
	@Nullable
	protected Locale parseLocaleValue(String locale) {
		return LocaleType.getValue(locale);
	}
	
	@Nullable
	protected String resolveLocal(HttpServletRequest request) {
		String locale = null;
		if (ResolverType.HEADER.equals(proper.getType())) {
			locale = request.getHeader(proper.getName());
		} else if (ResolverType.BODY.equals(proper.getType())) {
			locale = request.getParameter(proper.getName());
		}
		return locale;
	}
	
	public I18nProperties.Interceptor getProper() {
		return proper;
	}
	
	public void setProper(I18nProperties.Interceptor proper) {
		this.proper = proper;
	}
}
